package com.itheima.leyou.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Repository
public class StockDao {

    @Resource
    JdbcTemplate jdbcTemplate;

    public ArrayList<Map<String, Object>> getStockList(){
        /**
         *  `spu_id` BIGINT(20) NOT NULL COMMENT 'spu id',
         `title` VARCHAR(256) NOT NULL COMMENT '商品标题',
         `images` VARCHAR(1024) DEFAULT '' COMMENT '商品的图片，多个图片以‘,’分割',
         `stock` INT(8) UNSIGNED DEFAULT '9999' COMMENT '库存',
         `price` BIGINT(16) NOT NULL DEFAULT '0' COMMENT '销售价格，单位为分',
         `indexes` VARCHAR(32) DEFAULT '' COMMENT '特有规格属性在spu属性模板中的对应下标组合',
         `own_spec` VARCHAR(1024) DEFAULT '' COMMENT 'sku的特有规格参数键值对，json格式，反序列化时请使用linkedHashMap，保证有序',
         `enable` TINYINT(1) NOT NULL DEFAULT '1' COMMENT '是否有效，0无效，1有效',
         `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
         `update_time` TIMESTAMP NOT NULL COMMENT '最后修改时间',
         */
        String sql = "select id,spu_id, title, images, stock, price, indexes, own_spec, enable, create_time, update_time " +
                "from tb_sku order by spu_id";
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        list = (ArrayList<Map<String, Object>>) jdbcTemplate.queryForList(sql);
        return list;
    }

    public ArrayList<Map<String, Object>> getStock(String sku_id){
        String sql = "select tb_sku.spu_id, tb_sku.title, tb_sku.images, tb_sku.stock, tb_sku.price, tb_sku.indexes, " +
                "tb_sku.own_spec, tb_sku.enable, tb_sku.create_time, tb_sku.update_time,tb_spu_detail.description," +
                "tb_sku.id sku_id,tb_spu_detail.special_spec " +
                "from tb_sku " +
                "INNER JOIN tb_spu_detail ON tb_spu_detail.spu_id=tb_sku.spu_id " +
                "where tb_sku.id = "+sku_id;
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        list = (ArrayList<Map<String,Object>>) jdbcTemplate.queryForList(sql);
        return list;
    }

    public boolean insertLimitPolicy(Map<String, Object> map){
        Long policyId = System.nanoTime();
        policyId = policyId<0?-policyId:policyId;
        String sql = "INSERT INTO tb_limit_policy(id,sku_id,quanty,price,begin_time,end_time) " +
                "VALUES ("+policyId+",'"+map.get("sku_id")+"',"+map.get("quanty")+","+map.get("price")
                +",'"+map.get("begin_time")+"','"+map.get("end_time")+"') ";
        map.put("policyId",policyId);
        return jdbcTemplate.update(sql)==1;
    }
}
